package com.kfm.servlet;

import com.kfm.entity.User;
import com.kfm.service.UserService;
import com.kfm.util.Constant;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login3")
public class LoginServlet3 extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 验证码校验
        String captcha = req.getParameter(Constant.CAPTCHA_ATTR);
        // session 中存的 captcha
        HttpSession session = req.getSession();
//        String sessionCaptcha = (String) session.getAttribute(Constant.CAPTCHA_ATTR);
        if (!CaptchaUtil.ver(captcha, req)){
            // 验证码错误
            CaptchaUtil.clear(req);
            resp.sendRedirect("/");
            return;
        }
        CaptchaUtil.clear(req);
//        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captcha)){
//            // 验证码错误
//            resp.sendRedirect("/");
//            return;
//        }

        // 清除验证码
//        session.removeAttribute(Constant.CAPTCHA_ATTR);

        // 调用业务层
        User login = userService.login(username, password);

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        // 控制视图
        if (login == null){
            // 登录失败
            resp.sendRedirect("index.html");
            return;
        }

        // 登录成功
        // 存成功的标识
        session.setAttribute("user", login);

        writer.println("<h1>登录成功</h1>");
        writer.println("<h1>欢迎您，" + login.getName() + "</h1>");
        writer.println("<a href='image-list'>文件列表</a>");
    }
}
